//
//  Request.m
//  DDXueYa
//
//  Created by jiangfan on 2017/6/8.
//  Copyright © 2017年 Anfeek. All rights reserved.
//

#import "Request.h"

@implementation Request

+ (instancetype)shareManager{
    static Request *request = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        request = [[self alloc] init];
    });
    return request;
}

+ (void)postWithUrl:(NSString *)url prama:(NSDictionary *)dict{
    NSDate *currentDate = [NSDate date];
    NSString *timeStr = [NSString stringWithFormat:@"%ld",(long)[currentDate timeIntervalSince1970]];
    NSString *sign = [self getSignWithDict:dict];
    NSLog(@"%@",sign);
    //,@"app_crcert":@"3ffe170accff4fe1bdc4c1ec08af87dd"
    sign = [NSString stringWithFormat:@"%@&app_crcert=3ffe170accff4fe1bdc4c1ec08af87dd",sign];
    sign = [[sign lowercaseString] md5];
    NSLog(@"%@",sign);
    NSDictionary *parm = @{@"timestamp":timeStr,@"sign":sign};
//    NSDictionary *parm = @{@"sign":sign};

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    [manager POST:url parameters:parm progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
//排序生成sign
+ (NSString *)getSignWithDict:(NSDictionary *)dict{
    NSArray *keyArr = [dict allKeys];

    NSArray *newArr = [keyArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSString *valueStr = @"";
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < newArr.count; i++) {
        valueStr = [NSString stringWithFormat:@"%@=%@",newArr[i],dict[newArr[i]]];
        [arr addObject:valueStr];
    }
    valueStr = [arr componentsJoinedByString:@"&"];
    return valueStr;
    
}

@end
